﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace SPSilver.Common
{
	/// <summary>
	/// defines a class for the html-enriched fields of a list and provides a set of usefull classes
	/// </summary>
	public class HTML
	{
		// String _html = String.Empty;
		/// <summary>
		/// the html content as public property
		/// </summary>
		public String Html { get; private set; }


		/// <summary>
		/// the html content as public property
		/// </summary>
        public override String ToString() { return Html; }
		/// <summary>
		/// default constructor
		/// </summary>
		/// <param name="html">the field value as safeString()</param>
		public HTML(String html)
		{
			if (html != null)
				Html = html;
			else
				html = String.Empty;
		}

		/// <summary>
		/// Strips HTML from its tags and returns up to Length characters to the nearest space
		/// </summary>
		/// <param name="length"></param>
		/// <returns></returns>
		public String stripTags(int length)
		{
			string toReturn = stripTags();
			//το κόβουμε max length χαρακτήρες αν χρειάζεται
			if (toReturn.Length > 1)
			{
                if (toReturn.Length > length)
                {
                    toReturn = toReturn.Substring(0, length);
                    int lastSpace = toReturn.LastIndexOf(' ', length - 20);
                    if (lastSpace > 0)
                    {
                        toReturn = toReturn.Substring(0, lastSpace) + "...";
                    }
                }
			}
			else
			{
				toReturn = "...";
			}
			return toReturn;
		}

		/// <summary>
		/// Strips HTML from its tags
		/// </summary>
		/// <returns></returns>
		public String stripTags()
		{

			string toReturn = this.Html;
			if (!String.IsNullOrEmpty(toReturn))
			{
				toReturn = System.Text.RegularExpressions.Regex.Replace(toReturn, "<([^>]|\n)*?>", " ");
				toReturn = System.Text.RegularExpressions.Regex.Replace(toReturn, "\r\n", " ");
			}
			return toReturn;
		}
        public String HtmlEncode()
        {
            return System.Web.HttpUtility.HtmlEncode(this.Html);
        }
	}
}
